// im/pages/index.js
const TIM = require('../TUIKit/lib/tim-wx-sdk')
import {
  genTestUserSig
} from '../TUIKit/debug/GenerateTestUserSig'
import TIMUploadPlugin from '../TUIKit/lib/tim-upload-plugin'

const util = require("../../utils/util");
const api = require("../../api/api");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //客服类型
    type: '',

    //客服列表
    kefuList: [],

    //咨询师列表
    consultants: [],

    //客户帐号
    from: '',
    //客服帐号
    to: '',

    //显示弹出框
    showSelConsultants: false,

    //显示聊天
    showChatView: false,

    statusBarh:'', //状态栏高度

    customViewHeight:'', //自定义返回按钮高度

    iskefu:'kefu'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  
    let that = this;
    // if(getCurrentPages().length>2){
    //   let pages = getCurrentPages()
    //   let curPage = pages[pages.length - 2];
    //   let data = curPage.data;
    //   curPage.setData({
    //     'isBack':true
    //   });
    //   wx.navigateBack({delta: 2});
    // }

    const util = require("../../utils/util")
   // let iskefu =  options.iskefu;
    let imType = wx.getStorageSync('im:type');
    util.setiskefu(imType);

    this.setData({
      iskefu: imType,
    })
    // 类型，keFu:客服
    let type = options.type;

    //进入时有type
    this.setData({
      type: type,
    })

    //保存到缓存，退出时要使用
    if (type != "logout") {
      wx.setStorageSync('im:type', type)
      this.setData({
        type: type,
      })
    }

    if (type == "kefu") {
    
      //客服
      wx.setNavigationBarTitle({
        title: '客服',
      })
 
      //初始化
      this.initKeFu();
    } else if (type == "logout") {
      //退出登录
      this.logout()
    } else if (type == "consultants") {
      wx.setNavigationBarTitle({
        title: '咨询',
      })
    }
    console.log('退出返回============',type);
    let btn = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success:res => {
        console.log('设备信息',res)
        this.setData({
          statusBarh: res.statusBarHeight,
          customViewHeight:2 * (btn.top-res.statusBarHeight) + btn.height
        })
          }
      })



  },

  navigateBack(){
    wx.redirectTo({
      url: '/pages/home/index',
    }) 
  },

  /**
   * 注销
   */
  logout() {
    const util = require("../../utils/util")
    util.setTabbarActive("person");

    //从缓存中取出进入类型
    const im_type = wx.getStorageSync('im:type');

    // wx.showToast({
    //   title: '正在退出客服',
    //   icon: 'loading'
    // }).then(() => {
      wx.$TUIKit.logout();

      if (im_type == "kefu") {
        //客服时讲取回跳地址
        let url=wx.getStorageSync('im:redirectUrl');

        wx.navigateTo({
          url: url,
        })
      } else if (im_type == "consultants") {
        let url=wx.getStorageSync('im:redirectUrl');
        wx.navigateTo({
         // url: "/pages/service/index",
          url:"pages/consultants/consultants",
        })
        wx.setStorageSync('im:type', 'consultants')
      }
  //  })

  },
  /**
   * 初始化客服
   */
  initKeFu() {
    const that = this;

    //显示聊天窗口
    this.setData({
      showChatView: true,
    })

    //取得客服账号
    api.im.kefuList({
      success(resKefu) {

        console.log("kefuList,resKefu 获取客服账号= ==", resKefu);


        //保存客服列表
        that.setData({
          kefuList: resKefu.data.data,
        })

        //对话对象
        let to = resKefu.data.data.kefu[0];
        that.setData({
          to: to,
        })

        //获取用户IM账号
        api.im.getUserImAccount({
          to: to.im_account,
          success(resAcc) {
            // console.log("getUserImAccount,resAcc", resAcc);

            //客户信息
            that.setData({
              from: resAcc.data.data.from_im,
            })

            //初始化
            that.init()
          }
        })
      }

    })
  },
  initConsultants() {
    //const api=require("../../api/api");
    const that = this;

    //取得客服账号
    api.im.kefuList({
      success(resKefu) {
        // console.log("kefuList,resKefu", resKefu);

        //保存客服列表
        that.setData({
          kefuList: resKefu.data.data,
        })

        // 咨询师
        that.setData({
          consultants: resKefu.data.data.tutor,
        })

        console.log("that.data", that.data)

        //选择咨询师
        that.setData({
          showSelConsultants: true,
        })

        // //对话对象
        // let to = resKefu.data.data.kefu[0];
        // that.setData({
        //   to: to,
        // })


      }

    })
  },
  /**
   * 点击老师
   * @param {*} e 
   */
  tapTeacher(e) {
    console.log("tapTeacher,e", e)
    let im_account = e.currentTarget.dataset.im_account;
    let index = e.currentTarget.dataset.index;

    const that = this;

    //对话对象
    let to = this.data.consultants[index];
    that.setData({
      to: to,
    })

    //关闭弹出框
    this.setData({
      showSelConsultants: false,
      showChatView: true,
    })

    //获取用户IM账号
    api.im.getUserImAccount({
      to: im_account,
      success(resAcc) {
        // console.log("getUserImAccount,resAcc", resAcc);

        //客户信息
        that.setData({
          from: resAcc.data.data.from_im,
        })

        //初始化
        that.init()
      }
    })
  },

  /**
   * 初始化TIM
   */
  init() {
    const that = this;

    const userSig = that.data.from.user_sig;

    wx.$TUIKit = TIM.create({
      SDKAppID: util.getImSDKAPPID(),
    });
    wx.$chat_SDKAppID = util.getImSDKAPPID();
    wx.$chat_userID = that.data.from.im_account;
    wx.$chat_userSig = userSig;
    wx.$TUIKitTIM = TIM;
    wx.$TUIKit.registerPlugin({
      'tim-upload-plugin': TIMUploadPlugin
    });
    wx.$TUIKit.login({
      userID: that.data.from.im_account,
      userSig
    });
    wx.setStorage({
      key: 'currentUserID',
      data: [],
    });
    wx.$TUIKit.on(wx.$TUIKitTIM.EVENT.SDK_READY, that.onSDKReady, this);
  },
  onSDKReady() {
    const that = this;

    //设一个进入标识
    //wx.setStorageSync('isEnter', true);

    //TUIKit初始化
    const TUIKit = this.selectComponent('#TUIKit');
    TUIKit.init();
    TUIKit.startConversation(that.data.to.im_account);

    //拉起会话
    //console.log("TUIKit",TUIKit)
    //TUIKit.startConversation(that.data.from.im_account);



    // 修改个人标配资料
    let promise = wx.$TUIKit.updateMyProfile({
      nick: this.data.from.nickname,
      avatar: this.data.from.head_image,
      // gender: TIM.TYPES.GENDER_MALE,
      selfSignature: '顾客',
      allowType: TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
    });
    promise.then(() => {
      //发送消息
      // let message = wx.$TUIKit.createTextMessage({
      //   to: this.data.to.im_account,
      //   conversationType: TIM.TYPES.CONV_C2C,
      //   payload: {
      //     text: 'hello'
      //   }
      // })
      // wx.$TUIKit.sendMessage(message);

      //拉起会话
      // console.log("TUIKit",TUIKit)
      // TUIKit.startConversation(that.data.from.im_account);
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
      //咨询
      this.initConsultants();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.$TUIKit.off(wx.$TUIKitTIM.EVENT.SDK_READY, this.onSDKReady, this);
    this.logout();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})